package com.android.lovely.ui.activity

import android.Manifest
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.android.lovely.R
import com.android.lovely.data.CardItem
import com.android.lovely.data.ImageGenerationTask
import com.android.lovely.databinding.ActivityDownloadBinding
import com.android.lovely.databinding.ItemDownloadBinding
import com.android.lovely.ext.downloadImage
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.UIController
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.ui.fragment.HomeListItemDecoration
import com.android.lovely.ui.viewmodel.WorkTaskViewModel
import com.kotlin.extensions.context.ContextExt.activity
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.doOnIO
import com.kotlin.extensions.coroutine.CoroutineExt.doOnMain
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.withContext

/**
 *
 * @author why
 * @date 2025/4/13 15:55
 */
class DownloadActivity : BaseActivity<ActivityDownloadBinding>() {

    private val viewModel by viewModels<WorkTaskViewModel>()


    private val adapter by lazy {
        DownloadAdapter()
    }

    private val launcher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                download()
            }
        }

    override fun initView(savedInstanceState: Bundle?) {
        val bundle = intent.extras ?: return
        val task = bundle.getParcelable<ImageGenerationTask>("task")
        mBinding.llTop.addStatusBarMarginTop()
        mBinding.rv.addItemDecoration(HomeListItemDecoration(10.dp))
        mBinding.rv.layoutManager = GridLayoutManager(this, 2)
        mBinding.rv.adapter = adapter
        adapter.reportClick = {
            if (task != null) {
                this@DownloadActivity.startPage<OptimizationActivity>("user_id" to task.id)
            }
        }
        mBinding.ivLeft.clickable {
            finish()
        }
        mBinding.ivEdit.clickable {
            task?.let {
                startPage<AiGenerationActivity>("task" to it)
            }
        }
        mBinding.flex.displayProgress()
        viewModel.getImgDetail(mapOf("task_id" to (task?.id ?: 0)))
        mBinding.rv.layoutManager = GridLayoutManager(this, 2)
        mBinding.rv.adapter = adapter

        lifecycleScope.launchSafety() {
            viewModel.downLoad.collectLatest {
                val result = it.imageUrls
                adapter.updateList(result.map { ImageDownload(it) })
                if (result.isEmpty()) {
                    mBinding.flex.displayNoContent()
                } else {
                    mBinding.flex.displayMainContent()
                }
            }
        }
        mBinding.flex.setNoContentButton(getString(R.string.no_content))
        mBinding.flex.setNoContentIcon(R.drawable.icon_no_content)

        mBinding.save.clickable {
            download()
        }
    }

    private fun download() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            downloadMore()
        } else {
            launcher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
    }

    private fun downloadMore() {
        val list = adapter.getItems().filter { it.isSelected }
        lifecycleScope.launchWithLoading {
            doOnIO {
                var isSuccess = true
                val response = list.map {
                    async {
                        downloadImage(it.image).fold(
                            onSuccess = {
                                // 下载成功

                            },
                            onFailure = { e ->
                                // 处理错误
                                isSuccess = false
                            }
                        )
                    }
                }.awaitAll()
                doOnMain {
                    withContext(Dispatchers.Main) {
                        if (isSuccess) {
                            showToast(getString(R.string.download_successfully))
                        } else {
                            showToast(getString(R.string.download_image_failed))
                        }
                    }
                }

            }
        }
    }


    data class ImageDownload(
        val image: String = "", var isSelected: Boolean = true
    )

    inner class DownloadAdapter : BaseAdapter<ImageDownload, ItemDownloadBinding>() {

        var reportClick: () -> Unit = {}
        override fun bindViewWithHolderDetails(
            holder: ViewHolder,
            item: ImageDownload?,
            binding: ItemDownloadBinding,
            position: Int
        ) {
            item ?: return
            binding.apply {
                ivImage.loadWithPlaceholder(item.image, R.drawable.icon_item_holder)
                ivSelect.isSelected = item.isSelected
                tvReport.clickable {
                    reportClick.invoke()
                }
                root.clickable {
                    item.isSelected = !item.isSelected
                    notifyItemChanged(position)
                }
            }
        }

    }
}